const wx2my = require('../wx2my');
//author: LAEL
var user_api_url = 'https://gx.hippo365.cn';
var user_base_url = '';

function user_url(method) {
  return user_api_url + method;
}

function user_api(method, data, callback, failcb) {
  method = method || 'profile';
  data = data || {};
  let url = user_url(method);
  wx2my.request({
    method: 'POST',
    url: url,
    data: data,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'client': 'MiniProgram',
      'lng': user_trim(wx2my.getStorageSync('lng')),
      'lat': user_trim(wx2my.getStorageSync('lat')),
      // 'token': user_token(),
      'usercode': user_trim(wx2my.getStorageSync('usercode'))
    },
    withCredentials: true,
    crossDomain: true,
    success: function (apires) {
      apires = apires.data;

      if (apires.code == 1) {
        //保存数据
        // if (apires.data.token) user_save(apires.data.token);
        if (method == 'getOpenid' || method == 'register' || method == 'profile' || method == 'edit') {
          wx2my.setStorageSync('user', JSON.stringify(apires.data));
        } //退出登录


        if (method == 'logout') user_save(null);
      } else if (apires.code == -5) {
        user_save(null);

        if (method != 'getOpenid') {
          user_islogin(true, {
            method: method,
            data: data,
            callback: callback
          });
          return false;
        }
      }

      if (callback) callback(apires);
    },
    fail: function (apierr) {
      if (failcb) failcb(apierr);
    }
  });
}

function user_trim(str) {
  if (!str) return '';
  return (str + '').replace(/^\s+|\s+$/gm, '');
}

function user_data(field) {
  var user = wx2my.getStorageSync('user');
  if (user) user = JSON.parse(user);

  if (field) {
    if (user && user[field]) return user[field];
    return null;
  }

  return user;
}

function user_save(token) {
  wx2my.setStorageSync('token', token);
  if (!token) wx2my.setStorageSync('user', null);
}

function user_token() {
  return user_trim(wx2my.getStorageSync('token'));
} // 登录判断 放回给后台


function user_islogin(autologin, nextaction, pageurl, loginpage) {
  wx2my.showLoading({
    icon: 'none',
    mask: true,
    title: '加载中..'
  });
  var islogin = !!user_token();
  if (!autologin) return islogin;

  if (!islogin) {
    wx.login({
      success: function (e) {
        console.log(e);
        wx2my.hideLoading();
        wx.getUserInfo({
          success: function (res) {
            console.log(res);
            user_api('getOpenid', {
              code: e.code,
              nickname: res.userInfo.nickName,
              avatarUrl: res.userInfo.avatarUrl,
              encryptedData: res.encryptedData,
              iv: res.iv
            }, function (apires) {
              console.log(apires);

              if (apires.code == 1) {
                if (apires.data.token) user_save(apires.data.token);
                console.log(pageurl);

                if (pageurl) {
                  wx2my.reLaunch({
                    url: '/' + pageurl
                  });
                }

                if (nextaction) user_api(nextaction.method, nextaction.data, nextaction.callback);
              } else {
                wx2my.showToast({
                  none: 'none',
                  title: res.msg
                });
              }
            });
          },
          fail: function (apierr) {
            if (pageurl && !loginpage) {
              wx2my.reLaunch({
                url: '/pages/accredit/accredit?url=' + pageurl + ''
              });
            }
          }
        });
      }
    });
  }

  return islogin;
}

function user_urlparam(name) {
  var app = getApp();
  if (typeof app.globalData.get[name] == 'undefined') return '';
  return app.globalData.get[name];
} //定位


function user_location(cbfunc) {
  var lng = wx2my.getStorageSync('lng');
  var lat = wx2my.getStorageSync('lat');
  var temp = wx2my.getStorageSync('location');
  console.log(lng, lat, temp);
  if (lng && lat && temp && cbfunc) return cbfunc({
    "code": 1,
    "data": JSON.parse(temp)
  }); //有回调不重新读坐标

  wx2my.getLocation({
    type: 'gcj02',
    success: function (wxres) {
      wx2my.setStorageSync('lng', wxres.longitude);
      wx2my.setStorageSync('lat', wxres.latitude);
      wx2my.setStorageSync('location', JSON.stringify(wxres));
      if (cbfunc) cbfunc({
        "code": 1,
        "data": wxres
      });
    },
    cancel: function (wxres) {
      if (cbfunc) cbfunc({
        "code": 0,
        "data": wxres
      });
    },
    fail: function (wxres) {
      if (cbfunc) cbfunc({
        "code": 0,
        "data": wxres
      });
    },
    error: function (wxres) {
      if (cbfunc) cbfunc({
        "code": 0,
        "data": wxres
      });
    }
  });
} //初始化


var user_location_interval = null;

function user_init(pageurl, loginpage) {
  //app或其它端跳转判断登录
  var user_api_token = user_urlparam("token");
  if (user_api_token != '') user_save(user_api_token); //二维码

  var user_scene = user_urlparam("scene");

  if (user_scene) {
    wx2my.setStorageSync('usercode', user_scene);
  } //


  var user_usercode = user_urlparam("usercode");
  if (user_usercode != '') wx2my.setStorageSync('usercode', user_usercode); //主动登录微信

  if (typeof user_autologin == 'undefined' || user_autologin) user_islogin(true, false, pageurl, loginpage);

  if (user_islogin()) {
    user_location();
    clearInterval(user_location_interval);
    user_location_interval = setInterval(function () {
      user_location();
    }, 60000);
  }
}

module.exports = {
  user_api: user_api,
  user_location: user_location,
  user_data: user_data,
  user_islogin: user_islogin,
  user_init: user_init,
  //引用要运行此函数
  user_save: user_save
};